package com.mengdie.shuidi.ui.fragment;


import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mcxtzhang.indexlib.IndexBar.widget.IndexBar;
import com.mcxtzhang.indexlib.suspension.SuspensionDecoration;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.event.RandomEvent;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.MDModel;
import com.mengdie.shuidi.model.NewLineMode;
import com.mengdie.shuidi.ui.adapter.ProvinceAdapter;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class LineFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.tv_random_line)
    TextView mTvRandomLine;
    @Bind(R.id.recycleview)
    RecyclerView mRecyclerView;
    @Bind(R.id.tvSideBarHint)
    TextView mTvSideBarHint;
    @Bind(R.id.indexBar)
    IndexBar mIndexBar;

    private String mParam1;
    private String mParam2;
    private List<NewLineMode.RetDataBean> mProvinceList = new ArrayList<>();
    private ProvinceAdapter mProvinceAdapter;
    private LinearLayoutManager mManager;
    private SuspensionDecoration mDecoration;


    public static LineFragment newInstance(String param1, String param2) {
        LineFragment fragment = new LineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_line2, container, false);
        ButterKnife.bind(this, view);
//        if (mParam2.equals("2")) {
            getLineList();
            setListener();
//        }
        return view;
    }


    private void setListener() {

        mTvRandomLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new RandomEvent(true, true, mParam1.equals("true") ? true : false));
                getActivity().finish();
            }
        });

        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                List<NewLineMode.RetDataBean> data = (List<NewLineMode.RetDataBean>) adapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    if (i == position) {
                        data.get(i).setShow(true);
                    } else {
                        data.get(i).setShow(false);
                    }
                }

                mProvinceAdapter.notifyDataSetChanged();
            }
        });
    }


    /**
     * 获取线路列表
     */
    private void getLineList() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "server/line_list_new")
                .params("is_static", mParam1)
                .params("is_all", mParam2.equals("1") ? "1" : "2")
                .params("is_foreign", EmptyUtils.isEmpty(MDModel.getInstance().getIsOpen()) ? "2" : MDModel.getInstance().getIsOpen())
                .params("platform", "android")
                .params("session_id", MDAccountMgr.getInstance().getSessionId())
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jo = new JSONObject(s);
                            String ret = jo.getString("ret");
                            String code = jo.getString("code");
                            String msg = jo.getString("msg");
                            if (ret.equals("0") && code.equals("1")) {
                                NewLineMode newLineMode = new Gson().fromJson(s, NewLineMode.class);
                                mProvinceList = newLineMode.getData();
                                if (mProvinceList.size() == 0) {
                                    mIndexBar.setVisibility(View.GONE);
                                } else {
                                    mIndexBar.setVisibility(View.VISIBLE);
                                }
//                                mProvinceAdapter.setNewData(mProvinceList);
                                mManager = new LinearLayoutManager(getActivity());
                                mRecyclerView.setLayoutManager(mManager);
                                mDecoration = new SuspensionDecoration(getActivity(), mProvinceList);
                                mDecoration.setColorTitleBg(Color.parseColor("#f7f7f7"));

                                mRecyclerView.addItemDecoration(mDecoration);
                                // mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
                                mProvinceAdapter = new ProvinceAdapter(mProvinceList);
                                mRecyclerView.setAdapter(mProvinceAdapter);
                                mIndexBar.setmPressedShowTextView(mTvSideBarHint)//设置HintTextView
                                        .setNeedRealIndex(true)//设置需要真实的索引
                                        .setmLayoutManager(mManager);//设置RecyclerView的LayoutManager


                                mIndexBar.setmSourceDatas(mProvinceList).invalidate();

                                mDecoration.setmDatas(mProvinceList);//recycleview 单项布局上面的字母索引
                            } else if (ret.equals("1") && code.equals("-1")) {

                                mIndexBar.setVisibility(View.GONE);

                            }
                        } catch (Exception e) {
                        }
                    }
                });
    }

//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        ButterKnife.unbind(this);
//    }
}
